package com.king.armips.android.dialog;

import android.app.Dialog;
import android.content.Context;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.View;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.annotation.StringRes;

import com.king.armips.android.R;
import com.king.armips.android.utils.MainHandler;

public class LoadingDialog extends Dialog {

    private Context context;
    private long showTimestamp = 0;
    private final MainHandler handler = new MainHandler();

    private String message;
    private TextView tvLoadingMessage;

    public LoadingDialog(@NonNull Context context) {
        super(context, R.style.TransparentDialog);
        this.context = context;
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.dialog_loading);
        setCancelable(false);

        tvLoadingMessage = findViewById(R.id.tv_loading_message);

        if (message != null){
            setMessage(message);
        }

    }

    public void setMessage(@StringRes int resId){
        setMessage(context.getString(resId));
    }

    public void setMessage(String message) {
        this.message = message;
        if (tvLoadingMessage == null)
            return;
        if (TextUtils.isEmpty(message)){
            tvLoadingMessage.setVisibility(View.GONE);
        }
        else {
            tvLoadingMessage.setText(message);
            tvLoadingMessage.setVisibility(View.VISIBLE);
        }
    }

    @Override
    public void show() {
        super.show();
        handler.removeCallbacksAndMessages(null);
        showTimestamp = System.currentTimeMillis();
    }

    @Override
    public void dismiss() {
        super.dismiss();
        handler.removeCallbacksAndMessages(null);
    }

    public void showDelayed(long delayMillis){
        handler.removeCallbacksAndMessages(null);
        handler.postDelayed(this::show,delayMillis);
    }

    public void dismissDelayed(long delayMillis){
        long timeConsuming = System.currentTimeMillis() - showTimestamp;
        if(timeConsuming < delayMillis) {
            handler.postDelayed(this::dismiss, delayMillis - timeConsuming);
        }
        else {
            dismiss();
        }
    }


}
